package com.labtalk.admin.config.component;

import com.alibaba.fastjson.JSON;
import com.labtalk.admin.config.JwtTokenUtil;
import com.labtalk.admin.constant.HttpStatus;
import com.labtalk.admin.pojo.common.ResponseVo;
import com.labtalk.admin.pojo.entity.UserEntity;
import com.labtalk.admin.utils.ResponseOutputUtil;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author G-pointy
 * @Date 2022/8/10
 * @Description: Jwt登录授权过滤器 配置类
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Value("${jwt.header}")
    private String header;

    @Value("${jwt.tokenPrefix}")
    private String tokenPrefix;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头Authorization，带前缀的token：Bearer token
        String authHeader = request.getHeader(header);

        if (StringUtils.isEmpty(authHeader)) {
            filterChain.doFilter(request, response);
            return;
        }

        if (!authHeader.startsWith(tokenPrefix)) {
            ResponseOutputUtil.outputJson(response, ResponseVo.error(HttpStatus.TOKEN_INCORRECT, "token is incorrect", null));
            return;
        }

        // 获取token
        String token = authHeader.substring(tokenPrefix.length());

        // 校验token格式
        if (StringUtils.isEmpty(token)) {
            ResponseOutputUtil.outputJson(response, ResponseVo.error(HttpStatus.TOKEN_INCORRECT, "token is incorrect", null));
            return;
        }

        // token是否过期
        try {
            if (jwtTokenUtil.isTokenExpired(token)) {
                ResponseOutputUtil.outputJson(response, ResponseVo.error(HttpStatus.TOKEN_EXPIRED, "token is expired", null));
                return;
            }
        } catch (MalformedJwtException | SignatureException e) {
            ResponseOutputUtil.outputJson(response, ResponseVo.error(HttpStatus.TOKEN_INCORRECT, "token is incorrect", null));
            return;
        }

        Integer userId = jwtTokenUtil.getUserIdFromToken(token);
        if (userId == null) {
            ResponseOutputUtil.outputJson(response, ResponseVo.error(HttpStatus.UNAUTHORIZED, "获取用户失败，请登录", null));
            return;
        }

        // 获取登录时存到redis中的用户数据
        ValueOperations<Object, Object> valueOperations = redisTemplate.opsForValue();
        Object obj = valueOperations.get("user" + userId);
        UserEntity userEntity = JSON.parseObject((String) obj, UserEntity.class);
        if (Objects.isNull(userEntity)) {
            ResponseOutputUtil.outputJson(response, ResponseVo.error(HttpStatus.UNAUTHORIZED, "未登录，请登录", null));
            return;
        }

        // 将用户数据存到SecurityContextHolder中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userEntity, null, userEntity.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request, response);
    }
}
